import React, { useEffect, useState } from 'react';
import { Tree, Modal, Form, Input, Button, Tooltip } from '@arco-design/web-react';
import { IconPlus, IconMinus } from '@arco-design/web-react/icon';
import { Message } from '@arco-design/web-react';
import { IconCopy } from '@arco-design/web-react/icon';
import '@arco-design/web-react/dist/css/arco.css';
import initialTreeData from './const';

const App = () => {
  const [addedKeys, setAddedKeys] = useState(new Set());
  const [modalVisible, setModalVisible] = useState(false);
  const [parentKey, setParentKey] = useState(null);
  const [form] = Form.useForm();
  const [generatedSQL, setGeneratedSQL] = useState("");
  const [generateSQLFlag, setGenerateSQLFlag] = useState(false);

  const initializeTreeData = (data) => {
    const assignOriginalValues = (nodes) => {
      return nodes.map((node) => {
        if (node.children) {
          node.children = assignOriginalValues(node.children);
        }
        return {
          ...node,
          originalLft: node.lft,
          originalRgt: node.rgt,
        };
      });
    };
    return assignOriginalValues(data);
  };

  const [treeData, setTreeData] = useState(initializeTreeData(initialTreeData));
  const renderTree = (data) => {
    return data.map((node) => {
      const { title, key, name_item_label, app_id, children, id, name } = node;

      return {
        title: (
          <div style={{ display: 'flex', alignItems: 'center', backgroundColor: getNodeBackgroundColor(node) }}>
            <Tooltip
              content={
                <>
                  <div>id: {id}</div>
                  <div>名称: {name}</div>
                  <div>标签: {name_item_label}</div>
                  <div>应用ID: {app_id}</div>
                  <div>左值: {node.lft}</div>
                  <div>右值: {node.rgt}</div>
                </>
              }
            >
              <span style={{ marginRight: 10 }}>{title}</span> {/* 显示节点名称 */}
            </Tooltip>
            <div style={{ marginLeft: 'auto' }}>
              <IconPlus
                onClick={() => handleAddNode(key)}
                style={{ cursor: 'pointer', fontSize: 18, marginRight: 10 }}
              />
              {isNewNode(key) && (
                <IconMinus
                  onClick={() => handleDeleteNode(key)}
                  style={{ cursor: 'pointer', fontSize: 18 }}
                />
              )}
            </div>
          </div>
        ),
        key,
        children: children ? renderTree(children) : undefined,
      };
    });
  };

  const isNewNode = (key) => addedKeys.has(key);
  const handleAddNode = (parentKey) => {
    setParentKey(parentKey);
    setModalVisible(true);
  };

  const getNextKey = () => {
    const allKeys = [];
    const getAllKeys = (nodes) => {
      nodes.forEach(node => {
        allKeys.push(node.key);
        if (node.children) getAllKeys(node.children);
      });
    };
    getAllKeys(treeData);
    const maxKey = Math.max(...allKeys);
    return maxKey + 1;
  };
  const handleSubmit = (values) => {
    const { title, name_item_label, resource_id } = values;
    const newKey = getNextKey();
    const newNode = {
      id: newKey,
      name: title,
      title,
      key: newKey,
      name_item_label,
      app_id: 666666,
      lft: 999,
      rgt: 1000,
      resource_id
    };

    const newTreeData = addNodeToTree(treeData, parentKey, newNode);
    const restructuredTreeData = recalculateLftRgt(newTreeData);
    setTreeData(restructuredTreeData);
    setAddedKeys(new Set(addedKeys).add(newKey));
    setModalVisible(false);
    form.resetFields();
    Message.success('节点已添加');
    setGenerateSQLFlag(true);
  };

  const addNodeToTree = (tree, parentKey, newNode) => {
    return tree.map((node) => {
      if (node.key === parentKey) {
        return {
          ...node,
          children: node.children ? [...node.children, newNode] : [newNode],
        };
      }

      if (node.children) {
        return {
          ...node,
          children: addNodeToTree(node.children, parentKey, newNode),
        };
      }

      return node;
    });
  };

  const handleDeleteNode = (key) => {
    if (!isNewNode(key)) {
      Message.error('只能删除新节点');
      return;
    }
    const newTreeData = deleteNodeFromTree(treeData, key);
    const restructuredTreeData = recalculateLftRgt(newTreeData);
    setTreeData(restructuredTreeData);
    setAddedKeys(new Set([...addedKeys].filter(k => k !== key)));
    Message.success('节点已删除');
    setGenerateSQLFlag(true);
  };

  const deleteNodeFromTree = (tree, key) => {
    return tree.filter((node) => {
      if (node.key === key) {
        return false;
      }
      if (node.children) {
        node.children = deleteNodeFromTree(node.children, key);
      }
      return true;
    });
  };

  const recalculateLftRgt = (tree) => {
    let counter = 1;
    const assignLftRgt = (nodes) => {
      return nodes.map((node) => {
        const lft = counter++;
        let children = [];
        if (node.children) {
          children = assignLftRgt(node.children);
        }
        const rgt = counter++;
        return {
          ...node,
          lft,
          rgt,
          children,
        };
      });
    };

    const newTree = assignLftRgt(tree);
    return newTree;
  };

  const getNodeBackgroundColor = (node) => {
    if (!node.originalLft || !node.originalRgt) {
      return 'lightblue';
    }
    if (node.lft !== node.originalLft || node.rgt !== node.originalRgt) {
      return 'lightyellow';
    }
    return 'transparent';
  };

  const generateSQL = () => {
    let insertStatements = [];
    let updateStatements = [];

    const generateSQLForNode = (node) => {
      const { id, name, name_item_label, lft, rgt, app_id, resource_id, originalLft, originalRgt } = node;
      if (originalLft && originalRgt && (lft !== originalLft || rgt !== originalRgt)) {
        const updateSql = `UPDATE g7s_backstage_products_app_resource SET lft = ${lft}, rgt = ${rgt} WHERE id = ${id};`;
        updateStatements.push(updateSql);
      }
      if (!originalLft || !originalRgt) {
        const insertSql = `INSERT INTO g7s_backstage_products_app_resource (resource_id, name, name_item_label, lft, rgt, app_id) VALUES (${resource_id}, '${name}', '${name_item_label}', ${lft}, ${rgt}, ${app_id});`;
        insertStatements.push(insertSql);
      }
      if (node.children) {
        node.children.forEach(generateSQLForNode);
      }
    };
    treeData.forEach(generateSQLForNode);
    setGeneratedSQL({
      insert: insertStatements.join('\n'),
      update: updateStatements.join('\n')
    });
  };

  const handleCopyJson = () => {
      const jsonData = JSON.stringify(treeData, (key, value) => {
        // 过滤掉 originalLft 和 originalRgt
        if (key === 'originalLft' || key === 'originalRgt') {
          return undefined;
        }
        return value;
      }, 2);
      navigator.clipboard.writeText(jsonData).then(() => {
        Message.success('JSON 数据已复制');
      }).catch(err => {
        Message.error('复制失败');
      });
    };

  const handleCopySql = (sql) => {
    navigator.clipboard.writeText(sql).then(() => {
      Message.success('SQL 已复制');
    }).catch(err => {
      Message.error('复制失败');
    });
  };

  useEffect(()=> {
      if (generateSQLFlag) {
          generateSQL();
          setGenerateSQLFlag(false);
      }
  }, [generateSQLFlag])

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100vh' }}>
      <div style={{ height: '66vh', display: 'flex', overflowY: 'auto' }}>
        {/* 左侧树结构 */}
        <div style={{ flex: 1, padding: '20px', backgroundColor: '#f4f4f4', overflowY: 'auto' }}>
          <Tree treeData={renderTree(treeData)} />
        </div>

        {/* 右侧 JSON 数据 */}
        <div style={{ flex: 2, padding: '20px', backgroundColor: '#e6f7ff', overflowY: 'auto' }}>
          <Button icon={<IconCopy />} onClick={handleCopyJson}>复制 JSON</Button>
          <pre style={{ marginTop: '10px', whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>
            {JSON.stringify(treeData, (key, value) => {
              if (key === 'originalLft' || key === 'originalRgt' || key === 'key' || key === 'title') {
                return undefined;
              }
              return value;
            }, 2)}
          </pre>
        </div>
      </div>

      {/* 下半部分 - 生成 SQL 显示 */}
      <div style={{ height: '34vh', padding: '20px' }}>
        {/* 显示 INSERT 语句 */}
        {generatedSQL?.insert && (
            <div>
            <h3>INSERT 语句 <Button onClick={() => handleCopySql(generatedSQL.insert)} icon={<IconCopy />} style={{ marginTop: 10 }}></Button>
            </h3>
            <pre style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>
                {generatedSQL.insert}
            </pre>
            </div>
        )}

        {/* 显示 UPDATE 语句 */}
        {generatedSQL?.update && (
            <div>
            <h3>UPDATE 语句 <Button onClick={() => handleCopySql(generatedSQL.update)} icon={<IconCopy />} style={{ marginTop: 10 }}></Button>
            </h3>
            <pre style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>
                {generatedSQL.update}
            </pre>
            </div>
        )}
      </div>

      <Modal
        title="添加新节点"
        visible={modalVisible}
        onCancel={() => setModalVisible(false)}
        onConfirm={() => form.submit()}
      >
        <Form form={form} onSubmit={handleSubmit}>
          <Form.Item label="节点名称" field="title" rules={[{ required: true, message: '请输入节点名称' }]}>
            <Input />
          </Form.Item>
          <Form.Item label="名称标签" field="name_item_label" rules={[{ required: true, message: '请输入名称标签' }]}>
            <Input />
          </Form.Item>
          <Form.Item label="资源 ID" field="resource_id" rules={[{ required: true, message: '请输入资源 ID' }]}>
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default App;
